package com.example.wenqujingdian.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.wenqujingdian.R;
import com.example.wenqujingdian.adapter.FunctionModelAdapter;
import com.example.wenqujingdian.adapter.LocalBookSortAdapter;
import com.example.wenqujingdian.api.Contants;
import com.example.wenqujingdian.api.JsonDataManager;
import com.example.wenqujingdian.bean.BookDetailBean;
import com.example.wenqujingdian.bigdata.BigData;
import com.example.wenqujingdian.model.BookClassBean;
import com.example.wenqujingdian.model.LocalBookBean;
import com.example.wenqujingdian.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

public class LocalBooksActivity extends AppCompatActivity {

    private List<LocalBookBean> books;
    private View mNoUsbLayout;
    private TextView title;

    /*-------------------------------------*/
    private RecyclerView recyclerView;
    private RecyclerView recyclerViewType;
    private FunctionModelAdapter mAdapter;
    private LocalBookSortAdapter typeAdapter;
    private String classId;
//    private String specificPath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_books);
        Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath();
        View leftArrow = findViewById(R.id.local_left_arrow);
        title = findViewById(R.id.org_name);
        title.setText(getIntent().getStringExtra("title"));
        leftArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        checkPermission();
        initView();
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            List<String> applyPermissionList = new ArrayList<>();
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (applyPermissionList.size() == 0) {
                Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath();
//                initView();
                initData();
            } else {
                //请求所缺少的权限。
                String[] requestPermissions = new String[applyPermissionList.size()];
                applyPermissionList.toArray(requestPermissions);
                requestPermissions(requestPermissions, Contants.PERMISSION_STORAGE);
            }
        } else {
            Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath();
//            initView();
            initData();
        }

    }

    /**
     * 所有权限是否申请成功
     *
     * @param grantResults 权限获得结果的数组
     * @return ture:成功  false:失败
     */
    private boolean isAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                //如果有一个权限返回的是失败,返回false
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Contants.PERMISSION_STORAGE) {
            if (isAllPermissionsGranted(grantResults)) {
                Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath();
//                initView();
                initData();
            } else {
                ToastUtil.show("读写权限被拒绝");
            }
        }
    }

    private void initData() {
        JsonDataManager.getInstance().getLocalBookData(Contants.LOCAL_BOOK_JSON, this,
                new JsonDataManager.OnLocalListDataListener<LocalBookBean>() {
                    @Override
                    public void onSuccess(List<LocalBookBean> data) {
                        books = data;
                        mAdapter.setNewData(data);
                        getSortData();
                    }

                    @Override
                    public void onFail(String info) {
                        mNoUsbLayout = findViewById(R.id.no_usb_layout);
                        mNoUsbLayout.setVisibility(View.VISIBLE);
                    }
                });
    }

    private void getSortData() {
        JsonDataManager.getInstance().getBookClassData(Contants.BOOK_CLASS_JSON,
                LocalBooksActivity.this, new JsonDataManager.OnLocalListDataListener<BookClassBean>() {
                    @Override
                    public void onSuccess(List<BookClassBean> data) {
                        typeAdapter.setNewData(data);
                    }

                    @Override
                    public void onFail(String info) {

                    }
                });
    }

    private void initView() {
        GridLayoutManager manager;
        if (findViewById(R.id.tv_book2_land) != null) {
            //横屏显示
            manager = new GridLayoutManager(this, 5);
        } else {
            //竖屏显示
            manager = new GridLayoutManager(this, 3);
        }
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(manager);
        mAdapter = new FunctionModelAdapter(null, this);
        mAdapter.openLoadAnimation();
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LocalBookBean item = mAdapter.getItem(position);
                BookDetailBean bookDetailBean = new BookDetailBean();
                Intent intent = new Intent(LocalBooksActivity.this, LocalBookDetailsActivity.class);
                bookDetailBean.id = item.getBookId();
                bookDetailBean.news_tit = item.getBookTitle();
                bookDetailBean.author = item.getAuthor();
                bookDetailBean.jianjie = item.getEdition();
                bookDetailBean.news_source = item.getEdition();
                bookDetailBean.spic = Contants.SPICIFYPATH + item.getCover();
                bookDetailBean.url = item.getBookUrl();
                intent.putExtra("bookDetail", bookDetailBean);
                intent.putExtra("path", Contants.SPICIFYPATH);
                startActivity(intent);
            }
        });

        GridLayoutManager manager2;
        if (findViewById(R.id.tv_book2_land) != null) {
            //横屏显示
            manager2 = new GridLayoutManager(this, 5);
        } else {
            //竖屏显示
            manager2 = new GridLayoutManager(this, 3);
        }

        //manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerViewType = findViewById(R.id.recyclerViewType);
        recyclerViewType.setLayoutManager(manager2);
        typeAdapter = new LocalBookSortAdapter(this, null);
        typeAdapter.openLoadAnimation();
        recyclerViewType.setAdapter(typeAdapter);
        typeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Log.i(TAG, "onItemClick: position=" + position);
                Intent intent = new Intent(LocalBooksActivity.this, BookClassListActivity.class);
                classId = typeAdapter.getItem(position).getClassId();
                //ArrayList<LocalBookBean> bookByClassIdList = getBookByClassId();
               //intent.putParcelableArrayListExtra("list", bookByClassIdList);
                //改用静态成员来绕过页面数据传递大小限制
                BigData.bookByClassIdList = getBookByClassId();
                intent.putExtra("typeName", typeAdapter.getItem(position).getClassName());
                intent.putExtra("path", Contants.SPICIFYPATH);
                startActivity(intent);
            }
        });
    }

    /**
     * 根据id获取对应的图书
     *
     * @return
     */
    private ArrayList<LocalBookBean> getBookByClassId() {
        ArrayList<LocalBookBean> bookIdBeanList = new ArrayList<>();
        for (int i = 0; i < books.size(); i++) {
            LocalBookBean booksBean = books.get(i);
            String bookId = booksBean.getClassId();
            if (bookId != null) {
                if (!bookId.equals(classId)) {
                    continue;
                }
                bookIdBeanList.add(booksBean);
            }
        }
        return bookIdBeanList;
    }
}
